<template>
  <view class="container" style="padding: 0 30rpx 100rpx; background-color: #fff" v-if="isLoaded">
    <!-- 表单 -->
    <view class="content">
      <li-form>
        <li-form-item label="头像" :border="false">
          <li-upload-img :isSinglePic="true" :img-url="form.avatarImage" @afterChooseImage="afterChooseImage($event)" @deleteImg="deleteImg($event)" />
        </li-form-item>
        <li-form-item label="会员名称" :required="true">
          <li-input v-model="form.nickName" @blur="onBlurEvent($event)" prop="nickName" />
        </li-form-item>
        <li-form-item label="手机号" :required="true">
          <li-input v-model="form.mobile" @blur="onBlurEvent($event)" prop="mobile" />
        </li-form-item>
        <li-form-item label="性别">
          <li-picker
            v-model="form.sex"
            :rangeList="[
              {
                id: 1,
                text: '男'
              },
              {
                id: 2,
                text: '女'
              },
              {
                id: 3,
                text: '未知'
              }
            ]"
          ></li-picker>
        </li-form-item>
        <li-form-item label="会员等级">
          <li-picker v-model="form.grade" :rangeList="UserGradeList" range-key="title" />
        </li-form-item>
        <li-form-item label="会员分类">
          <li-picker v-model="form.userCategoryId" :rangeList="UserCategoryList" range-key="name" />
        </li-form-item>
        <li-form-item label="生日">
          <li-date-picker v-model="form.birthday" />
        </li-form-item>
        <li-form-item label="状态" :border="false">
          <!-- <li-radio
            v-model="form.status"
            :rangeList="[
              {
                id: 1,
                text: '正常'
              },
              {
                id: 2,
                text: '停用'
              }
            ]"
          /> -->
          <u-radio-group v-model="form.status">
            <u-radio size="20" activeColor="#edac2f" :customStyle="{ marginTop: '12rpx' }" label="正常" :name="1"></u-radio>
            <u-radio size="20" activeColor="#edac2f" :customStyle="{ marginLeft: '8px', marginTop: '12rpx' }" label="停用" :name="2"></u-radio>
          </u-radio-group>
        </li-form-item>
      </li-form>
    </view>
    <li-bottom-btns :zIndex="10" :mode="mode" v-on:btnDelClick="btnDelClick" v-on:btnEditOrSaveSubmitClick="btnEditOrSaveSubmitClick" />
  </view>
</template>
<script>
import { GetUserById, DelUserById, AddUser, EditUser, GetUserCategoryList, GetUserGradeList } from '../../../common/api.js';
import { uShowLoading, uHideLoading, uNavigateTo, umodal, utoast, uSetNavigationBarTitle } from '../../../utils/uniUtils.js';
import checker from '../../../common/graceChecker';
import { transfer, transferTypeEnum } from '../../../common/dataTransfer.js';
import { checkerType, modeEnum } from '../../../constants/normalConstants.js';
import { toastIconEnum } from '../../../constants/uiConstants.js';
import { corpId, storeId } from '../../../constants/apiConstants';
export default {
  async onLoad(options) {
    this.mode = options.mode == 'edit' ? 'edit' : 'add';
    uSetNavigationBarTitle((options.mode == 'edit' ? '编辑' : '新增') + this.subject);

    if (this.mode == modeEnum.edit) {
      this.id = options.id;
    }
  },

  async mounted() {
    try {
      uShowLoading();
      // 编辑模式
      if (this.mode == modeEnum.edit) {
        await this.getData();
      } else {
        // 新增模式
        this.form = {
          mobile: '',
          sex: 1,
          birthday: '1990-01-01',
          avatarImage: '',
          nickName: '',
          grade: 0,
          status: 1,
          userCategoryId: 0
        };
      }
      this.getOtherData();
    } catch (error) {
      console.log('error', error);
    } finally {
      this.isLoaded = true;
      uHideLoading();
    }
  },
  data() {
    return {
      modeEnum,
      subject: '会员', // 主题
      rootRoute: 'workbench',
      routeName: 'memberInfo',
      mode: 'add', // 模式
      isLoaded: false,
      id: null,
      /* 表单 */
      form: null,
      /* 弹窗 */

      // 数据转换器
      transferRules: [
        {
          name: 'mobile',
          type: transferTypeEnum.trim
        },
        {
          name: 'nickName',
          type: transferTypeEnum.trim
        }
      ],
      //表单校验规则
      rules: [
        {
          name: 'nickName',
          checkType: checkerType.endNotNull,
          errorMsg: '会员名称不能为空~~'
        },
        {
          name: 'mobile',
          checkType: checkerType.phoneno,
          errorMsg: '手机号格式不正确~~'
        }
      ],
      lock: false, // 节流锁

      /* 额外数据 */
      UserCategoryList: [],
      UserGradeList: []

      /* 额外校验规则 */
      /* 额外转换器 */
    };
  },

  methods: {
    onBlurEvent(e) {
      // console.log("e-->", e.mp.target.id);
      const name = e.currentTarget.id; // 获取输入框的id
      // 数据转换
      transfer(this.form, this.transferRules);
      // console.log(name, this.form[name]);

      // 表单校验
      if (name != null) {
        let rules = [];
        const rule = this.rules.find((item) => item.name == name);
        // console.log("name", name);
        // console.log("rules", this.rules);
        // console.log("rule", rule);
        // console.log("rule!=null", rule != null);

        if (rule != null) {
          rules.push(rule);
          const isOk = checker.check(this.form, rules);
          // console.log("isOk", isOk);

          if (!isOk) {
            utoast(checker.error, toastIconEnum.none);
          }
        }
      }
    },

    async getData() {
      this.form = (await GetUserById(this.id)).data;
    },

    async getOtherData() {
      // ..
      this.UserCategoryList = (await GetUserCategoryList()).data.list;
      this.UserGradeList = (await GetUserGradeList()).data.list;
      if (this.mode == modeEnum.add) {
        this.form.userCategoryId = this.UserCategoryList[0]?.id ?? 0;
        this.form.grade = this.UserGradeList[0]?.id ?? 0;
      }
    },

    async insertData() {
      return AddUser(this.form);
    },

    async delData() {
      return await DelUserById(this.id);
    },

    async editData() {
      return await EditUser(this.form);
    },

    async btnDelClick() {
      const res = await umodal();
      // 确定删除
      if (res) {
        const result = await this.delData();
        console.log(result);
        if (result.code != null && result.code == 0) {
          await utoast('删除成功！', toastIconEnum.success);
          this.disabled = true;
          setTimeout(() => {
            uNavigateTo(`/pages/${this.rootRoute}/${this.routeName}/list`);
          }, 1000);
        } else {
          await utoast('删除失败！', toastIconEnum.error);
        }
      }
    },

    async btnEditOrSaveSubmitClick() {
      //  节流锁
      if (this.lock) {
        return;
      }

      if (!(await umodal('确认要提交吗？'))) {
        return;
      }

      // 数据转换
      this.form = transfer(this.form, this.transferRules);

      // 表单校验
      let isOk = checker.check(this.form, this.rules);
      if (!isOk) {
        await utoast(checker.error, toastIconEnum.none);
        return;
      }

      //  提交表单
      const res = this.mode == modeEnum.edit ? await this.editData(this.form) : await this.insertData(this.form);
      if (res?.code == 0) {
        await utoast('操作成功');
        setTimeout(() => {
          uNavigateTo(`/pages/${this.rootRoute}/${this.routeName}/list`);
        }, 1000);
      } else {
        setTimeout(() => {
          this.lock = false;
        }, 2000);
      }
    },

    /* 表单事件 */
    afterChooseImage(e) {
      this.form.avatarImage = e.imgSrc;
    },
    deleteImg(e) {
      this.form.avatarImage = '';
    }

    /* 额外方法放下面，上面是主干方法 */

    //方法放上面
  }
};
</script>
<style lang="scss" scoped>
@import '~@/static/styles/commonStyle.scss';
</style>
